﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using SSPharma.Biz.HeThong;
using System.Data;
using SSPharma.Common;
using SSPharma.Model;
using WpfCustomControlLibrary;

namespace SSPharma.View.TimKiem
{
    /// <summary>
    /// Interaction logic for frmTimKiem.xaml
    /// </summary>
    public partial class frmTimKiem : Window
    {
        private BizTimKiem _BizTimKiem;
        private DataTable p_dtCauTruc;
        private DataTable p_dtDataHoanDoi;
        private DataTable p_dtDataGoc;
        private IList<cboCommon> p_lcboCommon;
        private bool p_bTwoGrid;
        private DataTable p_dtDataLuoiHai;
        private DataTable p_dtDelete;
        private string p_sStoreName;
        private string p_sParam;
        private string p_sValues;
        private string p_sDieuKienDau;
        private string p_sDieuKienCongThem;
        private IList<string> p_lReturnValues;
        //// add a delegate
        public delegate void IdentityValues(string key);
        //// add an event of the delegate type
        public event IdentityValues IdentityValue;

        #region Contructor
        public frmTimKiem()
        {
            InitializeComponent();
        }
        public frmTimKiem(string StoreName, string Param, string Values)
        {
            InitializeComponent();
            rowgird2.Height = new GridLength(0);
            rowgird3.Height = new GridLength(0);
            _BizTimKiem = new BizTimKiem();
            p_lcboCommon = new List<cboCommon>();
            p_lReturnValues = new List<string>();
            p_bTwoGrid = false;
            p_sStoreName = StoreName; //= "sp_frmOM" ;
            p_sParam = Param; //= "@strDKLoc|@strDKBatBuoc|@strFuture01|@strFuture02|@strFuture03|@strFuture04|@strFuture05";
            p_sValues = Values ;//= "|||||||";
            p_sDieuKienDau = Values.Substring(0, Values.IndexOf("|"));
            try
            {
                p_dtDataGoc = _BizTimKiem.ft_GetData(p_sStoreName, p_sParam, p_sValues);
                this.GenerateColumns();
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }

        #endregion

        #region Event
        private void g1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                int i = g1.SelectedIndex;
                if (i == -1)
                    return;
                var datarow =  p_dtDataHoanDoi.Rows[i];
                if (!p_bTwoGrid)
                {
                    string Id = datarow["KeyCode"].ToString();
                    if (!string.IsNullOrEmpty(Id))
                    {
                        this.IdentityValue(Id);
                        this.Close();
                    }
                }
                else
                {
                    DataRow dr = p_dtDataLuoiHai.AsEnumerable().SingleOrDefault(r => r.Field<string>("KeyCode") == p_dtDataHoanDoi.Rows[i]["KeyCode"].ToString());
                    if (dr != null)
                    {
                        MessageBox.Show("Dòng dữ liệu có KeyCode là: " + p_dtDataHoanDoi.Rows[i]["KeyCode"].ToString() + " đã được chọn.");
                        return;
                    }
                    datarow["Choose"] = "False";
                    p_dtDataLuoiHai.ImportRow(datarow);
                    if (!p_lReturnValues.Contains(datarow["KeyCode"].ToString()))
                        p_lReturnValues.Add(datarow["KeyCode"].ToString());
                    p_dtDataHoanDoi.Rows.RemoveAt(i);
                    g2.DataContext = p_dtDataLuoiHai;
                }
            }
            catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); }
        }

        private void g1_Data_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.Header = (e.Row.GetIndex() + 1).ToString();
        }

        private void g2_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                int i = g2.SelectedIndex;
                if (i == -1)
                    return;
                var datarow = p_dtDataLuoiHai.Rows[i];
                DataRow dr = p_dtDataHoanDoi.AsEnumerable().SingleOrDefault(r => r.Field<string>("KeyCode") == p_dtDataLuoiHai.Rows[i]["KeyCode"].ToString());
                if (dr == null)
                {
                    datarow["Choose"] = "False";
                    p_dtDataHoanDoi.ImportRow(datarow);
                    if (p_lReturnValues.Contains(datarow["KeyCode"].ToString()))
                        p_lReturnValues.Remove(datarow["KeyCode"].ToString());
                }
                p_dtDataLuoiHai.Rows.RemoveAt(i);
                g1.DataContext = p_dtDataHoanDoi;

            }
            catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); }
        }

        private void g2_Data_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.Header = (e.Row.GetIndex() + 1).ToString();
        }

        private void btnChon_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {
                string Id = string.Empty;
                if (!p_bTwoGrid)
                {
                    int i = g1.SelectedIndex;
                    if (i == -1)
                        return;
                    var datarow = p_dtDataHoanDoi.Rows[i];
                    Id = datarow["KeyCode"].ToString();
                    if (!string.IsNullOrEmpty(Id))
                    {
                        this.IdentityValue(Id);
                        this.Close();
                    }
                }
                else 
                {
                    for (int i = 0; i < p_dtDataHoanDoi.Rows.Count; i++)
                    {
                        if (p_dtDataHoanDoi.Rows[i]["Choose"].ToString() == "True" && !string.IsNullOrEmpty(p_dtDataHoanDoi.Rows[i]["KeyCode"].ToString())
                            && !Id.Contains(p_dtDataHoanDoi.Rows[i]["KeyCode"].ToString()))
                        {
                            p_lReturnValues.Add(p_dtDataHoanDoi.Rows[i]["KeyCode"].ToString());
                        }
                    }

                    if (p_lReturnValues.Count>0)
                    {
                        Id = string.Join("@#@",p_lReturnValues.ToArray());
                        this.IdentityValue(Id);
                        this.Close();
                    }
                }
            }
            catch (Exception ex) {}
        }
        
        private void cboDieuKien_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {

            if (cboDieuKien.SelectedValue != null && cboDieuKien.SelectedValue.ToString().Split('_').Last() == "Da")
            {
                stpValues.Children.Clear();
                Label lblTu = new Label();
                lblTu.Name = "lblTu";
                lblTu.Content = "Từ";
                lblTu.Height = 25;
                lblTu.Width = 30;
                AWDatePicker dptTu = new AWDatePicker();
                dptTu.Height = 25;
                dptTu.Width = 100;
                dptTu.Tag = "DATA";
                dptTu.Text = LibraryFormatConverter.SetStringDateDefault;
                Label lblDen = new Label();
                lblDen.Name = "lblTu";
                lblDen.Content = "Đến";
                lblDen.Height = 25;
                lblDen.Width = 35;
                AWDatePicker dptDen = new AWDatePicker();
                dptDen.Height = 25;
                dptDen.Width = 100;
                dptDen.Text = LibraryFormatConverter.SetStringDateDefault;
                dptDen.Tag = "DATA";
                stpValues.Children.Add(lblTu);
                stpValues.Children.Add(dptTu);
                stpValues.Children.Add(lblDen);
                stpValues.Children.Add(dptDen);
            }
            else if (cboDieuKien.SelectedValue != null && cboDieuKien.SelectedValue.ToString().Split('_').Last() == "Do")
            {
                stpValues.Children.Clear();
                Label lblTu = new Label();
                lblTu.Width = 10;
                AWTextBox txtSearch = new AWTextBox();
                txtSearch.Height = 25;
                txtSearch.Width = 250;
                txtSearch.Tag = "DATA";
                stpValues.Children.Add(lblTu);
                stpValues.Children.Add(txtSearch);
            }
            else
            {
                stpValues.Children.Clear();
                Label lblTu = new Label();
                lblTu.Width = 10;
                TextBox txtSearch = new TextBox();
                txtSearch.Height = 24;
                txtSearch.Width = 250;
                txtSearch.Tag = "DATA";
                stpValues.Children.Add(lblTu);
                stpValues.Children.Add(txtSearch);
            }
        }

        private void btnTimKiem_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {
                p_sValues = p_sValues.Substring(p_sValues.IndexOf("|"), p_sValues.Length - p_sValues.IndexOf("|"));
                if (cboDieuKien.SelectedValue != null && cboDieuKien.SelectedValue.ToString().Split('_').Last() == "Da")
                {
                    IList<string> listValues = this.GetDataSearch();
                    if (chkReset.IsChecked == true)
                    {
                        p_sValues = " and convert(datetime," + cboDieuKien.SelectedValue.ToString().Split('_').First() + ",103) BETWEEN convert(datetime,'"
                            + listValues[0] + "', 103) AND convert(datetime,'" + listValues[1] + "', 103)" + p_sValues;
                    }
                    else
                    {
                        p_sDieuKienCongThem += " and convert(datetime," + cboDieuKien.SelectedValue.ToString().Split('_').First() + ",103) BETWEEN convert(datetime,'"
                           + listValues[0] + "', 103) AND convert(datetime,'" + listValues[1] + "', 103)";
                        p_sValues = p_sDieuKienCongThem + p_sValues;

                    }
                }
                else if (cboDieuKien.SelectedValue != null)
                {
                    IList<string> listValues = this.GetDataSearch();
                    if (chkReset.IsChecked == true)
                    {
                        p_sValues = " and " + cboDieuKien.SelectedValue.ToString().Split('_').First() + " like N'%" + listValues[0] + "%'" + p_sValues;
                    }
                    else 
                    {
                        p_sDieuKienCongThem += " and " + cboDieuKien.SelectedValue.ToString().Split('_').First() + " like N'%" + listValues[0] + "%'";
                        p_sValues = p_sDieuKienCongThem + p_sValues;
                    }
                }
                p_dtDataGoc = _BizTimKiem.ft_GetData(p_sStoreName, p_sParam, p_sValues);
                p_dtDataGoc.Rows.RemoveAt(0);
                p_dtDataGoc.Rows.RemoveAt(0);
                p_dtDataHoanDoi.Clear();
                foreach (DataRow row in p_dtDataGoc.Rows)
                {
                    p_dtDataHoanDoi.ImportRow(row);
                }
                lblTongSo.Text = p_dtDataHoanDoi.Rows.Count > 0 ? p_dtDataHoanDoi.Rows.Count.ToString() : "";
                g1.DataContext = p_dtDataHoanDoi.AsDataView();
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }
        /// <summary>
        /// User: TAMNN 08/08/2014
        /// Mục đích: chọn tất cả
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkCheckAll_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            var chkCheckAll = (CheckBox)sender;
            if (chkCheckAll.IsChecked == true)
            {
                foreach (DataRow row in p_dtDataHoanDoi.Rows)
                {
                    row["Choose"] = "True";
                }
            }
            else
            {
                foreach (DataRow row in p_dtDataHoanDoi.Rows)
                {
                    row["Choose"] = "False";
                }
            }
        }
        
        private void g1_Module_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {
            try
            {
                int i = g1.SelectedIndex;
                if (i == -1)
                    return;
                DataRowView row = (DataRowView)g1.SelectedItems[0];
                int index = g1.CurrentCell.Column.DisplayIndex;
                if (index == 0)
                    row["Choose"] = "True";
            }
            catch (Exception ex) {}
        }
        
        private void g2_Module_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {
            try
            {
                int i = g2.SelectedIndex;
                if (i == -1)
                    return;
                DataRowView row = (DataRowView)g2.SelectedItems[0];
                int index = g2.CurrentCell.Column.DisplayIndex;
                if (index == 0)
                    row["Choose"] = "True";
            }
            catch (Exception ex) { }
        }

        private void btnX_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {
                IList<string> listdelete = new List<string>();
                for(int i = 0 ; i<p_dtDataHoanDoi.Rows.Count;i++)
                {
                    if (p_dtDataHoanDoi.Rows[i]["Choose"].ToString() == "True" && !string.IsNullOrEmpty(p_dtDataHoanDoi.Rows[i]["KeyCode"].ToString()))
                    {
                        DataRow dr = p_dtDataLuoiHai.AsEnumerable().SingleOrDefault(r => r.Field<string>("KeyCode") == p_dtDataHoanDoi.Rows[i]["KeyCode"].ToString());
                        if (dr != null)
                        {
                            MessageBox.Show("Dòng dữ liệu có KeyCode là: " + p_dtDataHoanDoi.Rows[i]["KeyCode"].ToString() +" đã được chọn.");
                            return;
                        }
                        p_dtDataHoanDoi.Rows[i]["Choose"] = "False";
                        p_dtDataLuoiHai.ImportRow(p_dtDataHoanDoi.Rows[i]);
                        listdelete.Add(p_dtDataHoanDoi.Rows[i]["KeyCode"].ToString());
                        if (!p_lReturnValues.Contains(p_dtDataHoanDoi.Rows[i]["KeyCode"].ToString()))
                            p_lReturnValues.Add(p_dtDataHoanDoi.Rows[i]["KeyCode"].ToString());
                    }
                }
                foreach(var item in listdelete)
                {
                    DataRow dr = p_dtDataHoanDoi.AsEnumerable().SingleOrDefault(r=> r.Field<string>("KeyCode") == item);
                    if(dr!=null)
                        p_dtDataHoanDoi.Rows.Remove(dr);
                }
                g2.DataContext = p_dtDataLuoiHai;
            }
            catch (Exception ex) { }
        }

        private void btnL_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {
                IList<string> listdelete = new List<string>();
                for (int i = 0; i < p_dtDataLuoiHai.Rows.Count; i++)
                {
                    if (p_dtDataLuoiHai.Rows[i]["Choose"].ToString() == "True" && !string.IsNullOrEmpty(p_dtDataLuoiHai.Rows[i]["KeyCode"].ToString()))
                    {
                        DataRow dr = p_dtDataHoanDoi.AsEnumerable().SingleOrDefault(r => r.Field<string>("KeyCode") == p_dtDataLuoiHai.Rows[i]["KeyCode"].ToString());
                        if (dr == null)
                        {
                            p_dtDataLuoiHai.Rows[i]["Choose"] = "False";
                            p_dtDataHoanDoi.ImportRow(p_dtDataLuoiHai.Rows[i]);
                        }
                        listdelete.Add(p_dtDataLuoiHai.Rows[i]["KeyCode"].ToString());
                        if (p_lReturnValues.Contains(p_dtDataLuoiHai.Rows[i]["KeyCode"].ToString()))
                            p_lReturnValues.Remove(p_dtDataLuoiHai.Rows[i]["KeyCode"].ToString());
                    }
                }
                foreach (var item in listdelete)
                {
                    DataRow dr = p_dtDataLuoiHai.AsEnumerable().SingleOrDefault(r => r.Field<string>("KeyCode") == item);
                    if (dr != null)
                        p_dtDataLuoiHai.Rows.Remove(dr);
                }
                g1.DataContext = p_dtDataHoanDoi;
            }
            catch (Exception ex) { }
        }

        private void btnReset_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {
                p_sValues = p_sValues.Substring(p_sValues.IndexOf("|"), p_sValues.Length - p_sValues.IndexOf("|"));
                p_dtDataGoc = _BizTimKiem.ft_GetData(p_sStoreName, p_sParam, p_sDieuKienDau + p_sValues.Substring(p_sValues.IndexOf("|"), p_sValues.Length - p_sValues.IndexOf("|")));
                p_dtDataGoc.Rows.RemoveAt(0);
                p_dtDataGoc.Rows.RemoveAt(0);
                p_dtDataHoanDoi.Clear();
                foreach (DataRow row in p_dtDataGoc.Rows)
                {
                    p_dtDataHoanDoi.ImportRow(row);
                }
                lblTongSo.Text = p_dtDataHoanDoi.Rows.Count > 0 ? p_dtDataHoanDoi.Rows.Count.ToString() : "";
                g1.DataContext = p_dtDataHoanDoi.AsDataView();
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }

        private void chkReset_Click(object sender, RoutedEventArgs e)
        {
            if(chkReset.IsChecked == true)
                p_sDieuKienCongThem = string.Empty;
        }
        #endregion

        #region Function
        public IList<string> GetDataSearch()
        {
            int count = stpValues.Children.Count;
            UIElementCollection aUIRoot = stpValues.Children;
            IList<string> listValues = new List<string>();
            for (int i = 0; i < count; i++)
            {
                string name = "";
                try
                {
                    UIElement element = aUIRoot[i];
                    Type type = element.GetType();
                    if (type == typeof(TextBox))
                    {
                        if (((TextBox)element).Tag != null && !string.IsNullOrEmpty(((TextBox)element).Tag.ToString()))
                        {
                            name = ((TextBox)element).Tag.ToString();
                            listValues.Add((((TextBox)element).Text == null) ? null : ((((TextBox)element).Text.Trim() == "") ? null : ((TextBox)element).Text));
                        }
                    }
                    else if (type == typeof(AWTextBox))
                    {
                        if (((AWTextBox)element).Tag != null && !string.IsNullOrEmpty(((AWTextBox)element).Tag.ToString()))
                        {
                            name = ((AWTextBox)element).Tag.ToString();
                            listValues.Add((((AWTextBox)element).Text == null) ? null : ((((AWTextBox)element).Text.Trim() == "") ? null : ((AWTextBox)element).Text));
                        }
                    }
                    else if (type == typeof(AWDatePicker))
                    {
                        if (((AWDatePicker)element).Tag != null && !string.IsNullOrEmpty(((AWDatePicker)element).Tag.ToString()))
                        {
                            name = ((AWDatePicker)element).Tag.ToString();
                            listValues.Add((((AWDatePicker)element).Text == null) ? null : ((((AWDatePicker)element).Text.Trim() == "") ? null : ((AWDatePicker)element).Text));
                        }
                    }
                }
                catch (Exception exception)
                {
                    throw new Exception(exception.Message + ": " + name);
                }
            }
            return listValues;
        }

        /// <summary>
        /// User: TAMNN 07/08/2014
        /// hàm lấy format grid
        /// </summary>
        /// <param name="Grid"></param>
        /// <param name="p_dtDataGoc"></param>
        public void GenerateColumns()
        {
            g1.Columns.Clear();
            p_dtCauTruc = p_dtDataGoc.Clone();
            p_dtCauTruc.ImportRow(p_dtDataGoc.Rows[0]);
            p_dtCauTruc.ImportRow(p_dtDataGoc.Rows[1]);
            p_dtDataGoc.Rows.RemoveAt(0);
            p_dtDataGoc.Rows.RemoveAt(0);
            DataRow dr1 = p_dtCauTruc.Rows[0];
            DataRow dr2 = p_dtCauTruc.Rows[1];
            p_dtDataHoanDoi = new DataTable();
            for (int j = 0; j < dr1.ItemArray.Length; j++)
            {


                if (!string.IsNullOrEmpty(dr1[j].ToString()) && !dr1[j].ToString().Equals("1") && !dr1[j].ToString().Equals("2"))
                {
                    string[] arr = dr1[j].ToString().Split('_');

                    #region căn lề
                    Style CellStyle;
                    //Style HeaderStyle;
                    if (arr.First() == "<")
                    {
                        CellStyle = new Style { TargetType = typeof(DataGridCell) };
                        CellStyle.Setters.Add(new Setter(Control.HorizontalAlignmentProperty, HorizontalAlignment.Left));
                        //HeaderStyle = new Style { TargetType = typeof(System.Windows.Controls.Primitives.DataGridColumnHeader) };
                        //HeaderStyle.Setters.Add(new Setter(Control.HorizontalAlignmentProperty, HorizontalAlignment.Left));

                    }
                    else if (arr.First() == ">")
                    {
                        CellStyle = new Style { TargetType = typeof(DataGridCell) };
                        CellStyle.Setters.Add(new Setter(Control.HorizontalAlignmentProperty, HorizontalAlignment.Right));
                        //HeaderStyle = new Style { TargetType = typeof(System.Windows.Controls.Primitives.DataGridColumnHeader) };
                        //HeaderStyle.Setters.Add(new Setter(Control.HorizontalAlignmentProperty, HorizontalAlignment.Right));
                    }
                    else
                    {
                        CellStyle = new Style { TargetType = typeof(DataGridCell) };
                        CellStyle.Setters.Add(new Setter(Control.HorizontalAlignmentProperty, HorizontalAlignment.Center));
                        //HeaderStyle = new Style { TargetType = typeof(System.Windows.Controls.Primitives.DataGridColumnHeader) };
                        //HeaderStyle.Setters.Add(new Setter(Control.HorizontalAlignmentProperty, HorizontalAlignment.Center));
                    }
                    #endregion

                    #region định dạng cột
                    if (arr.Length > 2 && arr[1] == "B" && j == 2)
                    {
                        p_bTwoGrid = true;
                        var checkall = new CheckBox();
                        checkall.Click += new RoutedEventHandler(chkCheckAll_Click);
                        //luoi 1
                        g1.Columns.Add(new DataGridCheckBoxColumn
                        {
                            Header = checkall,
                            Width = new DataGridLength(!string.IsNullOrEmpty(dr2[j].ToString()) ? Convert.ToInt32(dr2[j]) : 20),
                            Binding = new Binding(dr1.Table.Columns[j].ToString()),
                            //CellStyle = CellStyle
                        });
                        //luoi 2
                        g2.Columns.Add(new DataGridCheckBoxColumn
                        {
                            Header = checkall,
                            Width = new DataGridLength(!string.IsNullOrEmpty(dr2[j].ToString()) ? Convert.ToInt32(dr2[j]) : 20),
                            Binding = new Binding(dr1.Table.Columns[j].ToString()),
                            //CellStyle = CellStyle
                        });
                        rowgird2.Height = new GridLength(180);
                        rowgird3.Height = new GridLength(28);
                        p_dtDataHoanDoi.Columns.Add(dr1.Table.Columns[j].ToString(), typeof(bool));
                    }
                    else if (arr.Length > 2 && arr[1] == "B")
                    {
                        // luoi 1
                        g1.Columns.Add(new DataGridCheckBoxColumn
                        {
                            Header = arr.Last(),
                            Width = new DataGridLength(!string.IsNullOrEmpty(dr2[j].ToString()) ? Convert.ToInt32(dr2[j]) : 50),
                            Binding = new Binding(dr1.Table.Columns[j].ToString()),
                            IsReadOnly = true
                        });
                        // luoi 2
                        g2.Columns.Add(new DataGridCheckBoxColumn
                        {
                            Header = arr.Last(),
                            Width = new DataGridLength(!string.IsNullOrEmpty(dr2[j].ToString()) ? Convert.ToInt32(dr2[j]) : 50),
                            Binding = new Binding(dr1.Table.Columns[j].ToString()),
                            IsReadOnly = true
                        });
                        p_dtDataHoanDoi.Columns.Add(dr1.Table.Columns[j].ToString(), typeof(bool));
                        p_lcboCommon.Add(new cboCommon() { Id = dr1.Table.Columns[j].ToString() + "_" + arr[1], Name = arr.Last() });
                    }
                    else if (arr.Length > 2 && arr[1] == "Da")
                    {
                        // luoi 1
                        g1.Columns.Add(new DataGridTextColumn
                        {
                            Header = arr.Last(),
                            Width = new DataGridLength(!string.IsNullOrEmpty(dr2[j].ToString()) ? Convert.ToInt32(dr2[j]) : 50),
                            Binding = new Binding(dr1.Table.Columns[j].ToString()) {StringFormat="dd/MM/yyyy"},
                            IsReadOnly = true
                        });
                        // luoi 2
                        g2.Columns.Add(new DataGridTextColumn
                        {
                            Header = arr.Last(),
                            Width = new DataGridLength(!string.IsNullOrEmpty(dr2[j].ToString()) ? Convert.ToInt32(dr2[j]) : 50),
                            Binding = new Binding(dr1.Table.Columns[j].ToString()) { StringFormat = "dd/MM/yyyy" },
                            IsReadOnly = true
                        });
                        p_dtDataHoanDoi.Columns.Add(dr1.Table.Columns[j].ToString(), typeof(DateTime));
                        p_lcboCommon.Add(new cboCommon() { Id = dr1.Table.Columns[j].ToString() + "_" + arr[1], Name = arr.Last() });
                    }
                    else if (arr.Length > 2 && arr[1] == "Do")
                    {
                        string numberformat = ".000000000";
                        // luoi 1
                        g1.Columns.Add(new DataGridTextColumn
                        {

                            Header = arr.Last(),
                            Width = new DataGridLength(!string.IsNullOrEmpty(dr2[j].ToString()) ? Convert.ToInt32(dr2[j]) : 50),
                            Binding = arr.Length > 3 ? new Binding(dr1.Table.Columns[j].ToString()) { Converter = new StringFormatConverter(), ConverterParameter = "0:0,0" + (Convert.ToInt32(arr[2])> 0?(numberformat.Substring(0, Convert.ToInt32(arr[2])+1)):"") } :
                                        new Binding(dr1.Table.Columns[j].ToString()) { Converter = new StringFormatConverter() },
                            IsReadOnly = true,
                        });
                        // luoi 2
                        g2.Columns.Add(new DataGridTextColumn
                        {

                            Header = arr.Last(),
                            Width = new DataGridLength(!string.IsNullOrEmpty(dr2[j].ToString()) ? Convert.ToInt32(dr2[j]) : 50),
                            Binding = arr.Length > 3 ? new Binding(dr1.Table.Columns[j].ToString()) { Converter = new StringFormatConverter(), ConverterParameter = "0:0,0" + (Convert.ToInt32(arr[2]) > 0 ? (numberformat.Substring(0, Convert.ToInt32(arr[2]) + 1)) : "") } :
                                        new Binding(dr1.Table.Columns[j].ToString()) { Converter = new StringFormatConverter() },
                            IsReadOnly = true,
                        });
                        p_dtDataHoanDoi.Columns.Add(dr1.Table.Columns[j].ToString(), typeof(double));
                        p_lcboCommon.Add(new cboCommon() { Id = dr1.Table.Columns[j].ToString() + "_" + arr[1], Name = arr.Last() });
                    }
                    else
                    {
                        // luoi 1
                        g1.Columns.Add(new DataGridTextColumn
                        {
                            Header = arr.Last(),
                            Width = new DataGridLength(!string.IsNullOrEmpty(dr2[j].ToString()) ? Convert.ToInt32(dr2[j]) : 50),
                            Binding = new Binding(dr1.Table.Columns[j].ToString()),
                        });
                        // luoi 2
                        g2.Columns.Add(new DataGridTextColumn
                        {
                            Header = arr.Last(),
                            Width = new DataGridLength(!string.IsNullOrEmpty(dr2[j].ToString()) ? Convert.ToInt32(dr2[j]) : 50),
                            Binding = new Binding(dr1.Table.Columns[j].ToString()),
                        });
                        p_dtDataHoanDoi.Columns.Add(dr1.Table.Columns[j].ToString(), typeof(string));
                        p_lcboCommon.Add(new cboCommon() { Id = dr1.Table.Columns[j].ToString() + "_" + arr[1], Name = arr.Last() });
                    }
                    #endregion
                }
                else
                {
                    p_dtDataHoanDoi.Columns.Add(dr1.Table.Columns[j].ToString(), typeof(string));
                }
            }
            foreach (DataRow row in p_dtDataGoc.Rows)
            {
                p_dtDataHoanDoi.ImportRow(row);
            }
            p_dtDataLuoiHai = p_dtDataHoanDoi.Clone();
            p_dtDelete = p_dtDataHoanDoi.Clone();
            lblTongSo.Text = p_dtDataHoanDoi.Rows.Count > 0 ? p_dtDataHoanDoi.Rows.Count.ToString() : "";
            g1.DataContext = p_dtDataHoanDoi.AsDataView();
            cboDieuKien.ItemsSource = p_lcboCommon;
            cboDieuKien.SelectedIndex = 0;

        }
        

        #endregion

       
    }
}
